package model.service;

import java.util.HashMap;

import model.OnScreen;
import model.Snippet;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;

import android.util.JsonReader;
import android.util.Log;

public class JSONBehaviour extends ServiceBehaviour {

	private static final String TAG = JSONBehaviour.class.getSimpleName();

	@Override
	public void translateResponse(String response) throws JSONException
	{

		HashMap<String, Snippet> snippets = OnScreen.getInstance().getSnippets();
		String id;			
					
			
		JSONArray jsonArray = new JSONArray(response);
		for(int i = 0; i < jsonArray.length(); i ++)
		{
			JSONObject jsonSnippet;
//			String nextJson =  jsonArray.getString(i);
//			
//			if(isJSONValid(nextJson))
//			{
			
			jsonSnippet = jsonArray.getJSONObject(i);
			
			id = jsonSnippet.getString("ID");
			
			
			//If snippet already exists, update instead of create
			if(snippets.containsKey(id))
			{					
				snippets.get(id).setInformation(jsonSnippet.getBoolean("Value"));
				continue;
			}
			
			JSONObject jsonDimension = jsonSnippet.getJSONObject("Size");
			JSONObject jsonWorldCoord = jsonSnippet.getJSONObject("Coordinate");				
			
			Snippet snippet = createSnippet(
					id, 
					jsonWorldCoord.getInt("X"), jsonWorldCoord.getInt("Y"), jsonWorldCoord.getInt("Z"), 
					jsonDimension.getInt("Width"), jsonDimension.getInt("Height"), 
					jsonSnippet.getBoolean("Value"), jsonSnippet.getInt("Display")
				);
			
			snippets.put(
					id, 
					snippet
					);
				
				
//			}
//			else
//			{
//				Log.d(TAG, nextJson);
//				
////					when you split the 'bad' json on a " token, the array will look somewhat like this:
////					ID
////					:
////					<id>
////					so we take the <id> out of this array and try to get the snippet that is attached to that id.
//				String[] jsonParts = nextJson.split("\"");
//				for(int j = 0; j < jsonParts.length; j++)
//				{
//					if(jsonParts[j].equals("ID"))
//					{
//						OnScreen.getInstance().getWebServiceConnector().getSnippet(jsonParts[j+2]);
//						break;							
//					}
//				}
//				
//			}
		}
	}
	
	
	public boolean isJSONValid(String test)
	{
	    try {
	        new JSONObject(test);
	        return true;
	    } catch(JSONException ex) { 
	        return false;
	    }
	}
}
